<template>
  <!-- 新增编辑查看弹出框 -->
  <el-dialog :title="dialogTitle" v-model="editVisible" width="60%" :close-on-click-modal="closeOnClickModal" draggable @closed="closedFormDialog">
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px">
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="平台类型：" prop="type">
            <el-select v-model.trim="form.type" placeholder="平台类型" class="">
              <el-option v-for="item in selectPlatformType" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="版本号：" prop="version_code">
            <el-input v-model.trim="form.version_code" placeholder="版本号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-tooltip placement="top" content="格式：1.1.2 新版本号必须大于之前的版本号">
            <el-icon class="icon-wzg-config"><InfoFilled /></el-icon>
          </el-tooltip>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="20">
          <el-form-item label="描述：" prop="descriptions">
            <div class="w-container" v-for="(item, index) in form.descriptions" :key="item.id">
              <div class="w-content">
                <el-input v-model.trim="item.name"> </el-input>
                <el-icon class="w-i-plus" v-if="index === form.descriptions.length - 1" @click="showInput"><CirclePlus /></el-icon>
                <el-icon class="w-i-remove" @click="handleDeleteDesc(item.id)"><Remove /></el-icon>
              </div>
            </div>
            <div v-if="form.descriptions.length === 0">
              <el-icon class="w-i-plus" @click="showInput"><CirclePlus /></el-icon>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button :disabled="disabledbtn" @click="formStatus = 'none'">取 消</el-button>
        <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { postOrPutType } from "@/constants";
import type { ViewMode } from "@/types/common";
import { useState } from "@/hooks/useState.ts";
import type { IDictData } from "@/types/dict";
import type { IAppVersionDTO } from "@/types/appVersion";
import { commonAppVersionInfoListInfo } from "@/utils/api/appVersion";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  selectPlatformType: Array<IDictData>;
}
const { selectPlatformType } = defineProps<Props>();
const emit = defineEmits<{
  handleSuccess: [];
}>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });
const form = defineModel<IAppVersionDTO>("form", { required: true });

const editVisible = ref(false);
const formRef = useTemplateRef("formRef");

const rules = reactive({
  type: [{ required: true, message: "平台类型必选", trigger: "blur" }],
  version_code: [{ required: true, message: "版本号必填", trigger: "blur" }],
  descriptions: [{ required: true, message: "描述信息必填", trigger: "blur" }]
});

const dialogTitle = ref("新增");
const methodType = ref<postOrPutType>("POST");
const closeOnClickModal = ref(false);
const isDisabledbtn = ref(false);

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    dialogTitle.value = "查看";
    editVisible.value = true;
    isDisabledbtn.value = true;
    closeOnClickModal.value = true;
  },
  edit: () => {
    dialogTitle.value = "编辑";
    methodType.value = "PUT";
    editVisible.value = true;
  },
  add: () => {
    dialogTitle.value = "新增";
    methodType.value = "POST";
    editVisible.value = true;
  },
  none: () => {
    dialogTitle.value = "新增";
    methodType.value = "POST";
    editVisible.value = false;
    isDisabledbtn.value = false;
    closeOnClickModal.value = false;
    form.value.id = 0;
    form.value.descriptions = [];
    formRef.value?.resetFields();
    formRef.value?.clearValidate();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});

/* 点击新增tag标签 */
function showInput() {
  form.value.descriptions.push({
    id: new Date().getTime(),
    name: ""
  });
}

/* 删除描述信息 */
function handleDeleteDesc(id: number) {
  for (let i = 0; i < form.value.descriptions.length; i++) {
    if (form.value.descriptions[i].id === id) {
      form.value.descriptions.splice(i, 1);
      break;
    }
  }
}
// 关闭模态框
function closedFormDialog() {
  changeFormStatus("none");
}
// 切换formStatus
function changeFormStatus(state: ViewMode) {
  formStatus.value = state;
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  toggleState(true);
  commonAppVersionInfoListInfo(form.value, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      changeFormStatus("none");
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
</script>

<style lang="scss" scoped>
.w-i-plus {
  font-size: 30px;
  color: #409eff;
}
.w-i-remove {
  font-size: 30px;
  color: #f00;
}
.w-container {
  width: 100%;
}
.w-container + .w-container {
  margin-top: 10px;
}

.w-content {
  display: flex;
}
</style>
